import { useEffect, useState, useRef } from 'react'

type API<T, P> = (param?: P) => Promise<T>

export default function useFetch<T, P>(api: API<T, P>) {
  const param = useRef<P>()
  const [list, setList] = useState<T>()
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  function getList() {
    api(param.current).then(res => {
      setList(res)
      setLoading(false)
      setError('')
    }).catch(err => {
      setLoading(false)
      setError(err)
    })
  }

  useEffect(() => {
    loading && getList()
  }, [loading])

  return { 
    param, 
    setParam: (p: P) => param.current = p,
    list, 
    error, 
    loading, 
    setLoading 
  }
}